<?php

namespace App\Supports\Payment\Methods\Balance;

use App\Models\Order;
use App\Models\OrderItem;
use App\Models\User;
use App\Models\UserCoupon;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use App\Supports\Payment\Methods\Method;
use App\Events\OrderPaidEvent;
use App\Supports\Payment\Contracts\MethodPay;
use Illuminate\Validation\ValidationException;
use Illuminate\Support\Facades\Redis;
use App\Jobs\PayCacheOrderJob;

class PayCacheOrder extends Method implements MethodPay
{
	protected function isBalanceEnough($money,$user)
	{
		return big_decimal($user->balance)
			->isGreaterThanOrEqualTo($money);
	}
	
	public function validate($orderKey = null)
	{

		if(!Redis::exists($orderKey)){
			fail('请求订单不存在');
		}
		$orderListKey = Redis::zRange($orderKey,0, -1);
		
		$orderList = [];
		$money = big_decimal(0);
		
		foreach($orderListKey as $value){
			$order = Redis::hGetAll($value);


			if(empty($order)){

				fail('目标订单不存在');
			}

			if ($order['is_paid'] == true) {
				fail('目标订单已支付');
			}
			if(!empty($order->prive_vip)){

				$money = $money->plus($order->prive_vip);
			}

			$orderList[] = $order;
			
		}

		$userId = array_column($orderList,"user_id")[0];
		$user = User::find($userId);
		$this->user = $user;

		if (!$this->isBalanceEnough($money,$user)) {
			fail('可用账户余额不足');
		}

		return $orderList;
	}
	
	public function info($orderKey = null) {}
	
	public function pay($orderKey = null)
	{
		
		$orderList = $this->validate($orderKey);

		foreach($orderList  as $k=>$value){
			Redis::hMset($value['cid'],['paid_at'=> Carbon::now(),'paid_method' => 'balance','is_paid'=>true]);
			$this->user->addOrderToPendingCache($value['cid']);
			$this->user->delOrderFromUnpaidCache($value['cid']);
			$queue = app()->environment('local') ? 'default' : 'paid_order';
			dispatch(new PayCacheOrderJob($this->user,$value['cid']))->onQueue($queue);
		}
		
	}
}
